/**
 * @description 用户信息、登录、退出登录
 */
import $storage from '@/sheep/utils/storage';
import admin from '@/app/admin/api';
import { defineStore } from 'pinia';
import app from './app';

const account = defineStore({
  id: 'account',
  state: () => ({
    isLogin: !!$storage.get('token'),
    info: {
      nickname: '',
      avatar: '',
    },
    menuRules: [], // 菜单权限
    pageRules: [], // 页面权限
    apiRules: [], // 请求权限
  }),
  actions: {
    /**
     * @description 登录
     * @param {*} formData
     */
    async login(formData) {
      return await admin.account.login(formData);
    },

    /**
     * @description 设置token
     * @param {*} token
     */
    setToken(token = '') {
      this.token = token;
      if (token == '') {
        this.isLogin = false;
        $storage.remove('token');
      } else {
        this.isLogin = true;
        $storage.set('token', token);
      }
    },

    /**
     * @description 获取用户信息
     */
    async getInfo() {
      const { error, data } = await admin.account.info();

      let lastLogin = $storage.get('lastLogin');
      if (lastLogin) {
        lastLogin.info = {
          avatar: data.avatar,
          nickname: data.nickname,
          account: data.account,
        };
        $storage.set('lastLogin', lastLogin);
      }
      this.info = data;
      return data;
    },

    /**
     * @description 获取用户菜单权限规则
     */
    async getRules() {
      const { error, data } = await admin.account.rules();
      if (error === 0) {
        this.menuRules = data.menu; // 设置菜单规则
        this.pageRules = data.permission; // 设置页面权限
        this.apiRules = data.permission; // 设置功能权限
        return data;
      }
    },

    /**
     * @description 退出登录
     * @param force
     */
    async logout(force = false) {
      let that = this;
      if (!force) {
        await admin.account.logout();
      }
      setTimeout(function () {
        that.info = {};
        that.setToken();
        that.setRules({ menu: [], page: [], api: [] });
        app().setTaskbar({ list: [], history: [] });
        window.location = location.pathname;
      }, 0);
    },

    /**
     * @description 设置菜单规则
     * @param payload
     */
    setRules(payload) {
      this.menuRules = payload.menu; // 设置菜单规则
      this.pageRules = payload.permission; // 设置页面权限
      this.apiRules = payload.permission; // 设置功能权限
    },
  },
});

export default account;
